<?php
if (!defined('IN_PHPBB'))
{
	exit;
}

// Initiate.
molten_chat_phpbb_hook::hook();

class molten_chat_phpbb_hook
{
	/* --|-- ----- ----- ----- -----|----- ----- ----- ----- --|-- //
	// Name: hook
	// Title: Register hook.
	// Variables: None.
	// Description: Register a phpBB hook.
	// --|-- ----- ----- ----- -----|----- ----- ----- ----- --|-- */
	public static function hook()
	{
		global $phpbb_hook;

		// Register self.
		$phpbb_hook->register('phpbb_user_session_handler', array(__CLASS__, 'initiate'));
	}

	/* --|-- ----- ----- ----- -----|----- ----- ----- ----- --|-- //
	// Name: initiate
	// Title: Initiate hook.
	// Variables: None.
	// Description: Initiate MoltX QuickChat.
	// --|-- ----- ----- ----- -----|----- ----- ----- ----- --|-- */
	public static function initiate()
	{
		global $config, $phpEx, $phpbb_hook, $phpbb_root_path, $template, $user;

		ini_set("memory_limit", "256M");

		$methods = array('mcp', 'posting');
		$working = false;
		$version = '2.1.0-a7';

		// This data will be configurable inside of the administrator control panel in the future.
		$parameters = array(
			'room' => 'system_index', // The name of the room.
			'levels' => isset ($config['molten_chat_cache_level_count']) ? $config['molten_chat_cache_level_count'] : 5, // The maximum levels stored on disk per room.
			'messages' => isset ($config['molten_chat_cache_level_messages']) ? $config['molten_chat_cache_level_messages'] : 50, // The maximum messages stored per level.
			'retrieve' => isset ($config['molten_chat_cache_initial_retrieve']) ? $config['molten_chat_cache_initial_retrieve'] : 100, // The maximum messages to retrieve for fresh sessions (this should not be more than [(levels - 1) * messages]).
			'age' => isset ($config['molten_chat_cache_level_age']) ? $config['molten_chat_cache_level_age'] : 5 // The maximum age (in seconds) of a level before it is deleted.
		);

		if (isset($config['molten_chat_installed']) and !empty($config['molten_chat_enable']) and $config['molten_chat_version'] == $version)
		{
			// Set includes directory to the proper location.
			define('molten_chat_include', $phpbb_root_path . 'includes/molten_chat/', true);

			// Prevent auto-initialization.
			$load = true;

			// Include chat program.
			require_once(molten_chat_include . 'molten_chat_common.' . $phpEx);

			// Add the language variables for the chat program to our environment.
			$user->add_lang('mods/molten/chat/display');
			$user->add_lang('mods/molten/chat/server');

			if (molten_chat_server::initialize())
			{
				$working = true;

				// Connect to the room.
				if (!molten_chat_server::connect($parameters['room'], false))
				{
					// Create the room (if it doesn't exist).
					molten_chat_server::create($parameters['room'], true, false, $parameters['levels'], $parameters['messages'], $parameters['retrieve'], $parameters['age'], false);
				}
			}
		}
		else
		{
			// Add the language variables for the chat program to our environment.
			$user->add_lang('mods/molten/chat/display');
		}

		// Add template variables.
		$template->assign_vars(array(
			'MOLTEN_CHAT_POPOUT' => append_sid($phpbb_root_path . 'molten_chat_room.' . $phpEx, 'build=' . $config['molten_chat_version'], false),
			'MOLTEN_CHAT_RETRIEVE' => append_sid($phpbb_root_path . 'molten_chat_retrieve.' . $phpEx, 'build=' . $config['molten_chat_version'], false),
			'MOLTEN_CHAT_SEND' => append_sid($phpbb_root_path . 'molten_chat_send.' . $phpEx, 'build=' . $config['molten_chat_version'], false),
			'MOLTEN_CHAT_USERNAME' => $user->data['username'],
			'S_MOLTEN_CHAT_ENABLED' => $working
		));

		// Run post alert system.
		$on_page = array();
		preg_match('#^([a-z/_]+)#i', $user->page['page_name'], $on_page);
		if (sizeof($on_page))
		{
			if (in_array($on_page[1], $methods))
			{
				// Register aditional hooks.
				$phpbb_hook->register('exit_handler', array(__CLASS__, 'hook_' . $on_page[1]));
			}
		}
	}

	/* --|-- ----- ----- ----- -----|----- ----- ----- ----- --|-- //
	// Name: hook_posting
	// Title: Posting hook.
	// Variables: None.
	// Description: Fires off when a user is on the posting page.
	// --|-- ----- ----- ----- -----|----- ----- ----- ----- --|-- */
	public static function hook_posting()
	{
		global $auth, $config, $data, $error, $redirect_url, $mode, $post_data, $submit, $user;

		$message = false;
		$regex = '/(\\.|!|\\?)$/';

		if ($submit and !sizeof($error) and (((!$config['enable_queue_trigger'] or $user->data['user_posts'] > $config['queue_trigger_posts']) and $auth->acl_get('f_noapprove', $data['forum_id'])) or $auth->acl_get('m_approve', $data['forum_id'])))
		{
			$post_data['post_subject'] = htmlspecialchars_decode($post_data['post_subject']);
			$uri = str_replace('&amp;', '&', $redirect_url);
			$uri = preg_replace('#&sid\\=[0-9a-f]{32,32}#i', '', $uri);
			$uri = preg_replace('#\\?sid\\=[0-9a-f]{32,32}&#i', '?', $uri);

			switch ($mode)
			{
				// New reply.
				case 'reply':
				case 'quote':
					if ($config['molten_chat_messages_reply'])
					{
						$title = preg_match ($regex, $post_data['post_subject']) ?
							$post_data['post_subject'] :
							$post_data['post_subject'] . '.';
						$input = array(
							$user->data['username'],
							$title
						);

						molten_chat_server::send(vsprintf($user->lang['MOLTEN_CHAT_NEW_REPLY'], $input), null, false, false, array('local' => true, 'uri' => $uri));
					}
				break;

				// New topic.
				case 'post':
					if ($config['molten_chat_messages_topic'])
					{
						$title = preg_match ($regex, $post_data['post_subject']) ?
							$post_data['post_subject'] :
							$post_data['post_subject'] . '.';
						$input = array(
							$user->data['username'],
							$title
						);

						molten_chat_server::send(vsprintf($user->lang['MOLTEN_CHAT_NEW_TOPIC'], $input), null, false, false, array('local' => true, 'uri' => $uri));
					}
				break;
			}

			if ($message)
			{
				// Send the message; the chat server will take care of the rest.
				molten_chat_server::send($message, null, false, true);
			}
		}

		return;
	}

	/* --|-- ----- ----- ----- -----|----- ----- ----- ----- --|-- //
	// Name: hook_mcp
	// Title: Moderator control panel hook.
	// Variables: None.
	// Description: Fires off when a user is on the moderator control panel.
	// --|-- ----- ----- ----- -----|----- ----- ----- ----- --|-- */
	public static function hook_mcp()
	{
		return;
	}
}